﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;
using System.Web.Security;
using System.Configuration;

namespace TireService.Web.View.OperatorView
{
    public partial class ServiceList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack != true)
            {
                int ServiceCarId = Convert.ToInt32(Request.QueryString["ServiceCarId"]);
                DateTime ScheduleDate = Convert.ToDateTime(Request.QueryString["ScheduleDate"]);

                lblServiceCarId.Text = ServiceCarId.ToString();
                lblScheduleDate.Text = ScheduleDate.ToShortDateString();

                LoadDayPlan(ServiceCarId, ScheduleDate);
            }
        }

        public void LoadDayPlan(int ServiceCarId, DateTime ScheduleDate)
        {
            TireServiceDB db = new TireServiceDB();
            gvDayPlan.DataSource = db.ServiceCarScheduleDetailViews.Where(p => p.ServiceCarId == ServiceCarId & p.ScheduleDate == ScheduleDate).OrderBy(d => d.StartTime).ToList();
            gvDayPlan.DataBind();
        }

        /// <summary>
        /// Postback function that updates overview of dayplan for a specific servicecar and scheduledate
        /// </summary>
        protected void gvDayPlan_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            // Get values (0: ServiceCarId, 1: ScheduleDate)
            string[] param = e.Parameters.Split('|');

            LoadDayPlan(Convert.ToInt32(param[0]), Convert.ToDateTime(param[1]));
        }

        /// <summary>
        /// Gridview function that runs when databinding - Changes colors based on customerconfirmed value
        /// </summary>
        protected void gvDayPlan_HtmlRowPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableRowEventArgs e)
        {
            if (e.RowType != DevExpress.Web.ASPxGridView.GridViewRowType.Data) return;

            int servicetype = Convert.ToInt32(gvDayPlan.GetRowValuesByKeyValue(e.KeyValue, "ScheduleDetailTypeId"));

            if (servicetype == (int)Shared.ScheduleDetailType.Available)
            {
                e.Row.BackColor = System.Drawing.Color.White;
            }
            if (servicetype == (int)Shared.ScheduleDetailType.Blocked)
            {
                e.Row.BackColor = System.Drawing.Color.Red;
            }
            if (servicetype == (int)Shared.ScheduleDetailType.ServiceDrive)
            {
                // Get customerconfirmed value - based on that rows will be formated
                bool CustomerConfirmed = Convert.ToBoolean(gvDayPlan.GetRowValuesByKeyValue(e.KeyValue, "CustomerConfirmed"));

                if (CustomerConfirmed)
                {
                    e.Row.BackColor = System.Drawing.Color.DarkGreen;
                }
                else
                {

                    e.Row.BackColor = System.Drawing.Color.Orange;
                }
                bool WorkCompleted = Convert.ToBoolean(gvDayPlan.GetRowValuesByKeyValue(e.KeyValue, "WorkCompleted"));
                if (WorkCompleted)
                {
                    e.Row.BackColor = System.Drawing.Color.DarkSlateBlue;
                }
            }
        }

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvDayPlan_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn CarDetailDescription: Show car details
            if (e.Column.FieldName == "CarDetailDescription")
            {
                // Get values
                string CarBrandDescription = Convert.ToString(e.GetListSourceFieldValue("CarBrandDescription"));
                string Model = Convert.ToString(e.GetListSourceFieldValue("Model"));
                string Color = Convert.ToString(e.GetListSourceFieldValue("Color"));

                e.Value = CarBrandDescription + " - " + Model + " (" + Color + ")";
            }
            
            // Format UnBoundColumn ServiceTaskDetails: Show taskdetails contained
            if (e.Column.FieldName == "ServiceTaskDetails")
            {
                // Get taskid
                int TaskId = Convert.ToInt32(e.GetListSourceFieldValue("TaskId"));

                TireServiceDB db = new TireServiceDB();

                List<TaskDetailView> taskdetails = db.GetTaskDetailsExtendedView(TaskId);

                string detail = string.Empty;

                foreach (TaskDetailView taskdetail in taskdetails)
                {
                    if (detail.Length > 0)
                    {
                        detail += ", " + taskdetail.Description;
                    }
                    else
                    {
                        detail += taskdetail.Description;
                    }
                }

                e.Value = detail;
            }
        }

        /// <summary>
        /// Callback function that handles completion of servicedrive
        /// </summary>
        protected void callMarkServiceCompleted_Callback(object sender, CallbackEventArgs e)
        {
            // Get values (0: ServiceCarScheduleDetailId, 1: CompletionType (0: Send email+Trustpilot, 1: Send email or 2: Only close, no email)
            string[] param = e.Parameter.Split('|');

            int ServiceCarScheduleDetailId = Convert.ToInt32(param[0]);
            int CompletionType = Convert.ToInt32(param[1]);

            // Instantiate database
            TireServiceDB db = new TireServiceDB();

            // Get UserId
            Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

            //string CustomerFeedbackURL = ConfigurationManager.AppSettings["CustomerFeedbackURL"].ToString();

            // Submit for each task (to avoid email being send out where database changes is not done)
            TaskBLL taskBLL = new TaskBLL();
            if (CompletionType == 0)
            {
                // Mark completed + Trustpilot email
                taskBLL.MarkServiceDriveAsCompletedByServiceCarScheduleDetailId(db, ServiceCarScheduleDetailId, true, false, true, userid, false);
            }
            if (CompletionType == 1)
            {
                // Mark completed + email
                taskBLL.MarkServiceDriveAsCompletedByServiceCarScheduleDetailId(db, ServiceCarScheduleDetailId, true, false, false, userid, false);
            }
            if (CompletionType == 2)
            {
                // Mark completed, no email
                taskBLL.MarkServiceDriveAsCompletedByServiceCarScheduleDetailId(db, ServiceCarScheduleDetailId, false, false, false, userid, false);
            }
            

            // Dispose database connection
            db.Dispose();
        }

        /// <summary>
        /// Callback function that handles other action
        /// </summary>
        protected void callOtherAction_Callback(object sender, CallbackEventArgs e)
        {
            // Get values (0: ServiceCarScheduleDetailId, 1: Action (0: Replan service, 1: complete service - customer kept tires)
            string[] param = e.Parameter.Split('|');

            int ServiceCarScheduleDetailId = Convert.ToInt32(param[0]);
            int Action = Convert.ToInt32(param[1]);

            // Instantiate database
            TireServiceDB db = new TireServiceDB();

            // Get UserId
            Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

            TaskBLL taskBLL = new TaskBLL();

            // Get servicecarscheduledetail record
            ServiceCarScheduleDetail scheduledetail = db.GetServiceCarScheduleDetail(ServiceCarScheduleDetailId);
            if (scheduledetail == null)
            {
                throw new ArgumentException("Valgt tidsrum eksistere ikke - venligst prøv igen.");
            }

            // Check if timeslot is booked or blocked
            if (scheduledetail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.Available)
            {
                throw new ArgumentException("Valgt tidsrum er ikke booket - venligst vælg et andet.");
            }

            // Get related task
            Task task = db.GetTask(Convert.ToInt32(scheduledetail.TaskId));

            if (Action == 0)
            {
                // Delete planned service and set it to replan
                if (scheduledetail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive)
                {                 
                    // Change status on task
                    task.TaskTypeStatusId = (int)Shared.TaskTypeStatus.ServiceDrive_Replan;

                    // Fetch all TaskDetails to see if Task contain TireChange
                    List<TaskDetail> taskdetails = db.GetTaskDetails(task.TaskId);

                    foreach (TaskDetail taskdetail in taskdetails)
                    {
                        if (taskdetail.TaskDetailTypeId == (int)Shared.TaskDetailType.ServiceDrive_ChangeTire)
                        {
                            Car car = db.GetCar(Convert.ToInt32(task.CarId));

                            // Update car with new status        
                            car.CarStatusId = (int)Shared.CarStatus.AwaitsTireChangePlanning;

                            // Send internal email to ourself on this
                            string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
                            bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
                            string message = String.Format("Følgende sag blev ikke taget - spørg montør til baggrund:<br><br>KundeId: {0}<br><br>Bil: {1}", task.CustomerId.ToString(), car.RegistrationNumber);


                            Shared emailBLL = new Shared();
                            emailBLL.SendEmail(emailaddress, emailaddress, message, "Sag blev ikke taget: " + task.CustomerId.ToString(), true, test, null, null, null);
                        }
                    }
                }

                // Update timeslot - reset to available status
                ServiceCarScheduleDetailBLL detailBLL = new ServiceCarScheduleDetailBLL();
                detailBLL.MakeServiceCarScheduleDetailAvailable(db, scheduledetail, true);

                // Commit changes to database
                db.SubmitChanges();
            }
            if (Action == 1)
            {
                // Add extra taskdetail to task (ex. TireSet returned)
                TaskDetail newtaskdetail = new TaskDetail();
                taskBLL.AddTaskDetailToExistingTask(db, task, newtaskdetail, (int)Shared.TaskDetailType.ServiceDrive_ReturnTire, 1, null, userid, true);

                // Commit changes to database
                db.SubmitChanges();

                // Mark complete service and set customer kept tires
                taskBLL.MarkServiceDriveAsCompletedByServiceCarScheduleDetailId(db, ServiceCarScheduleDetailId, true, false, false, userid, false);

                // Commit changes to database
                db.SubmitChanges();

                // Send internal email to ourself on this
                string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
                bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
                string message = String.Format("Service færdigmeldt og kunde har beholdt sine hjul:<br><br>KundeId: {0}<br><br>Bil: {1}", task.CustomerId.ToString(), db.GetCarRegistrationNumber(Convert.ToInt32(scheduledetail.CarId)));


                Shared emailBLL = new Shared();
                emailBLL.SendEmail(emailaddress, emailaddress, message, "Kunde har beholdt hjul: " + task.CustomerId.ToString(), true, test, null, null, null);
            }

            // Dispose database connection
            db.Dispose();
        }

        /// <summary>
        /// Callback function that get next or previous scheduledate
        /// </summary>
        protected void callbackGetScheduleDate_Callback(object sender, CallbackEventArgs e)
        {
            // Prepare input values (0: next(1) or previous(-1), 1: servicecarid, 2: current scheduledate)
            string[] param = e.Parameter.Split('|');

            // Get value (servicecarscheduledetailid)
            int Method = Convert.ToInt32(param[0]);
            int ServiceCarId = Convert.ToInt32(param[1]);
            DateTime CurrentScheduleDate = Convert.ToDateTime(param[2]);

            // Instantiate database
            TireServiceDB db = new TireServiceDB();

            if (Method < 0)
            {
                // Previous date
                List<ServiceCarSchedule> schedules = db.ServiceCarSchedules.Where(p => p.ServiceCarId == ServiceCarId & p.ScheduleDate < CurrentScheduleDate).OrderByDescending(p => p.ScheduleDate).ToList();

                if (schedules.Count > 0)
                {
                    ServiceCarSchedule schedule = schedules.First();

                    // Return date
                    e.Result = schedule.ScheduleDate.ToShortDateString();
                }
            }

            if (Method > 0)
            {
                // Next date

                List<ServiceCarSchedule> schedules = db.ServiceCarSchedules.Where(p => p.ServiceCarId == ServiceCarId & p.ScheduleDate > CurrentScheduleDate).OrderBy(p => p.ScheduleDate).ToList();

                if (schedules.Count > 0)
                {
                    ServiceCarSchedule schedule = schedules.First();

                    // Return date
                    e.Result = schedule.ScheduleDate.ToShortDateString();
                }
            }
            
            // Dispose database connection
            db.Dispose();
        }
    }
}